package com.bm.specialvehiclefordispatcher.activity.main;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.bm.corelibs.logic.BaseLogic.NListener;
import com.bm.corelibs.utils.ToastMgr;
import com.bm.specialvehiclefordispatcher.App;
import com.bm.specialvehiclefordispatcher.R;
import com.bm.specialvehiclefordispatcher.activity.BaseActivity;
import com.bm.specialvehiclefordispatcher.activity.login.LoginActivity;
import com.bm.specialvehiclefordispatcher.activity.mysites.MySitesActivity;
import com.bm.specialvehiclefordispatcher.activity.mywallet.RechargeMoneyActivity;
import com.bm.specialvehiclefordispatcher.activity.order.OrderDetailActivity;
import com.bm.specialvehiclefordispatcher.bean.BaseData;
import com.bm.specialvehiclefordispatcher.bean.Price;
import com.bm.specialvehiclefordispatcher.bean.TruckStyle1;
import com.bm.specialvehiclefordispatcher.constants.Constant;
import com.bm.specialvehiclefordispatcher.logics.FindTrucksManager;
import com.bm.specialvehiclefordispatcher.logics.LoginManager;
import com.bm.specialvehiclefordispatcher.views.CustomDialog;
import com.bm.specialvehiclefordispatcher.views.DatePickerDialog;
import com.bm.specialvehiclefordispatcher.views.DatePickerDialog.onDateSelectedListener;
import com.bm.specialvehiclefordispatcher.views.PopMenu;
import com.bm.specialvehiclefordispatcher.views.PopMenu.OnMenuItemClickedListener;
import com.bm.specialvehiclefordispatcher.views.SelectCountView;
import com.bm.specialvehiclefordispatcher.views.SelectCountView.OnCountChangedListener;

public class FindTrucksActivity extends BaseActivity implements OnClickListener, OnMenuItemClickedListener, OnCountChangedListener, OnFocusChangeListener, onDateSelectedListener {

	public static final String TRUCK_TYPE = "TRUCK_TYPE";
	private static final int DECIMAL_DIGITS = 1;

	private ImageView iv_close, iv_header1, iv_header2, iv_header3, iv_time, iv_condition;
	private TextView tv_header1, tv_header2, tv_header3, tv_time, tv_condition, tv_price, tv_condition_name, tv_sumprice;
	private EditText et_volume, et_count, et_remarks;
	private SelectCountView sc_addprice;
	private View v_header1, v_header2, v_header3;
	private Button btn_submit;
	private LinearLayout ll_loading;

	private int current = 0;
	private List<View> headerViews = new ArrayList<View>();
	private List<TextView> headerTextViews = new ArrayList<TextView>();
	private List<ImageView> headerImageViews = new ArrayList<ImageView>();

	private int resId[] = { R.drawable.find_header1, R.drawable.find_header2, R.drawable.find_header3 };
	private int sResId[] = { R.drawable.find_header1_s, R.drawable.find_header2_s, R.drawable.find_header3_s };

	private FindTrucksManager manager = new FindTrucksManager();
	private List<TruckStyle1> styles;
	private PopMenu menu;
	private DatePickerDialog datePickerDialog;
	private CustomDialog dialog;

	private Price price;
	private double sumPrice = 0;
	private String selectedDate = "", remarks = "";
	private double volume = 0;
	private int count = 0;

	private InputMethodManager imm;

	InputFilter lengthfilter = new InputFilter() {
		public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
			// 删除等特殊字符，直接返回
			if ("".equals(source.toString())) {
				return null;
			}
			String dValue = dest.toString();
			String[] splitArray = dValue.split("\\.");
			if (splitArray.length > 1) {
				String dotValue = splitArray[1];
				int diff = dotValue.length() + 1 - DECIMAL_DIGITS;
				if (diff > 0) {
					return source.subSequence(start, end - diff);
				}
			}
			return null;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_find_trucks);
		findViews();
		init();
		addListeners();
	}

	@Override
	public void findViews() {
		iv_close = (ImageView) findViewById(R.id.iv_close);
		iv_header1 = (ImageView) findViewById(R.id.iv_header1);
		iv_header2 = (ImageView) findViewById(R.id.iv_header2);
		iv_header3 = (ImageView) findViewById(R.id.iv_header3);
		iv_time = (ImageView) findViewById(R.id.iv_time);
		iv_condition = (ImageView) findViewById(R.id.iv_condition);

		tv_header1 = (TextView) findViewById(R.id.tv_header1);
		tv_header2 = (TextView) findViewById(R.id.tv_header2);
		tv_header3 = (TextView) findViewById(R.id.tv_header3);
		tv_time = (TextView) findViewById(R.id.tv_time);
		tv_condition = (TextView) findViewById(R.id.tv_condition);
		tv_price = (TextView) findViewById(R.id.tv_price);
		tv_condition_name = (TextView) findViewById(R.id.tv_condition_name);
		tv_sumprice = (TextView) findViewById(R.id.tv_sumprice);

		et_volume = (EditText) findViewById(R.id.et_volume);
		et_count = (EditText) findViewById(R.id.et_count);
		et_remarks = (EditText) findViewById(R.id.et_remarks);

		v_header1 = (View) findViewById(R.id.v_header1);
		v_header2 = (View) findViewById(R.id.v_header2);
		v_header3 = (View) findViewById(R.id.v_header3);

		sc_addprice = (SelectCountView) findViewById(R.id.sc_addprice);
		btn_submit = (Button) findViewById(R.id.btn_submit);

		ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
	}

	@Override
	public void init() {
		imm = ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE));
		current = getIntent().getIntExtra(TRUCK_TYPE, 0);
		initLists();
		if (App.TruckStyleList == null || App.TruckStyleList.size() <= 0)
			manager.getStyles(getStyleListener());
		else {
			ll_loading.setVisibility(View.GONE);
			styles = App.TruckStyleList;
			setStyleTitles();
			onTruckClicked();
		}
		//et_volume.setFilters(new InputFilter[] { lengthfilter });
		tv_sumprice.setText(sumPrice + "");
		v_header1.post(new Runnable() {
			@Override
			public void run() {
				et_volume.requestFocus();
				menu = new PopMenu(mActivity, tv_condition);
				datePickerDialog = new DatePickerDialog(mActivity);
				menu.setOnMenuItemClickedListener(FindTrucksActivity.this);
				datePickerDialog.setonDateSelectedListener(FindTrucksActivity.this);
				dialog = new CustomDialog(mActivity);
			}
		});
	}

	private void initLists() {
		headerViews.add(v_header1);
		headerViews.add(v_header2);
		headerViews.add(v_header3);

		headerTextViews.add(tv_header1);
		headerTextViews.add(tv_header2);
		headerTextViews.add(tv_header3);

		headerImageViews.add(iv_header1);
		headerImageViews.add(iv_header2);
		headerImageViews.add(iv_header3);
	}

	@Override
	public void addListeners() {
		iv_close.setOnClickListener(this);
		iv_header1.setOnClickListener(this);
		iv_header2.setOnClickListener(this);
		iv_header3.setOnClickListener(this);
		iv_time.setOnClickListener(this);
		iv_condition.setOnClickListener(this);
		tv_header1.setOnClickListener(this);
		tv_header2.setOnClickListener(this);
		tv_header3.setOnClickListener(this);
		tv_time.setOnClickListener(this);
		tv_condition.setOnClickListener(this);
		btn_submit.setOnClickListener(this);
		et_volume.setOnFocusChangeListener(this);
		sc_addprice.setOnCountChangedListener(this);
	}

	@Override
	public void onClick(View v) {
		et_volume.clearFocus();
		switch (v.getId()) {
		case R.id.iv_close:
			imm.hideSoftInputFromWindow(FindTrucksActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			finish();
			break;

		case R.id.iv_header1:
		case R.id.tv_header1:
			current = 0;
			onTruckClicked();
			break;

		case R.id.iv_header2:
		case R.id.tv_header2:
			current = 1;
			onTruckClicked();
			break;

		case R.id.iv_header3:
		case R.id.tv_header3:
			current = 2;
			onTruckClicked();
			break;

		case R.id.iv_time:
		case R.id.tv_time:
			datePickerDialog.show();
			break;

		case R.id.iv_condition:
		case R.id.tv_condition:
			menu.setData(styles.get(current).stylePrice);
			menu.show();
			break;

		case R.id.btn_submit:
			checkInput();
			break;
		}
	}

	private void onTruckClicked() {
		if (current != 0)
			et_count.setText("1");
		changeTruckType();
		setStyles();
		price = null;
		sumPrice = 0;
		tv_sumprice.setText(sumPrice + "");
		sc_addprice.setCount(0);
	}

	private void changeTruckType() {
		for (int i = 0; i < headerTextViews.size(); i++) {
			if (i == current) {
				headerViews.get(i).setBackgroundColor(getResources().getColor(R.color.main));
				headerTextViews.get(i).setTextColor(getResources().getColor(R.color.main));
				headerImageViews.get(i).setImageResource(sResId[i]);
				// headerImageViews.get(i).setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			} else {
				// int size = DisplayUtil.dip2px(mActivity, 52);
				headerViews.get(i).setBackgroundResource(0x00000000);
				headerTextViews.get(i).setTextColor(0xFF888888);
				headerImageViews.get(i).setImageResource(resId[i]);
				// headerImageViews.get(i).setLayoutParams(new LinearLayout.LayoutParams(size, size));
			}
		}
	}

	private NListener<BaseData> getStyleListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				System.out.println("onResponse");
				if (data.status == Constant.STATUS_OK) {
					if (data.data.TruckStyleList != null) {
						ll_loading.setVisibility(View.GONE);
						styles = data.data.TruckStyleList;
						// App.TruckStyleList = styles;
						setStyleTitles();
						onTruckClicked();
					}
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}

	private void setStyleTitles() {
		for (int i = 0; i < styles.size(); i++) {
			if (i >= 3)
				return;
			headerTextViews.get(i).setText(styles.get(i).styleName);
		}
	}

	private void setStyles() {
		tv_condition.setText("");
		tv_price.setText("");
		tv_condition_name.setText(styles.get(current).stylePrice.get(0).conditionName);
	}

	@Override
	public void onMenuItemClicked(int position, Object data) {
		price = (Price) data;
		tv_price.setText(price.price + " 元/立方");
		countSumPrice();
	}

	@Override
	public void onCountChanged(SelectCountView view, int count) {
		countSumPrice();
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (!hasFocus) {
			countSumPrice();
		}
	}

	private void countSumPrice() {
		String sVolume = et_volume.getText().toString().trim();

		if (price == null || sVolume.length() <= 0)
			return;

		int addPrice = sc_addprice.getCount();
		double unitPrice = price.price;
		double volume = 0;
		try {
			volume = Double.valueOf(sVolume);
		} catch (Exception e) {
		}

		sumPrice = volume * (unitPrice + addPrice);

		tv_sumprice.setText(new java.text.DecimalFormat("0.00").format(sumPrice));
	}

	@Override
	public void onDateSelected(String date) {
		selectedDate = date;
		tv_time.setText(date.substring(5, date.length()));
	}

	@SuppressLint("SimpleDateFormat")
	private void checkInput() {
		String sVolume = et_volume.getText().toString().trim();
		String sCount = et_count.getText().toString().trim();
		remarks = et_remarks.getText().toString().trim();

		if (sVolume.length() <= 0) {
			ToastMgr.show("请填写期望的需求方量");
			return;
		}
		
		if(sVolume.split("[.]").length > 1 && sVolume.split("[.]")[1].length() > 1) {
			ToastMgr.show("需求方量请保留一位小数");
			return;
		}

		if (sCount.length() <= 0) {
			ToastMgr.show("请填写期望的车辆数");
			return;
		}

		volume = 0;
		count = 0;
		try {
			volume = Double.valueOf(sVolume);
			count = Integer.valueOf(sCount);
		} catch (Exception e) {
			ToastMgr.show(R.string.find_err2);
			return;
		}

		if (volume <= 0 || count <= 0) {
			ToastMgr.show("需求方量或数量必须大于0");
			return;
		}

		if (selectedDate.length() <= 0) {
			ToastMgr.show("请填写期望的用车时间");
			return;
		}

		if (price == null) {
			ToastMgr.show("请选择" + styles.get(current).stylePrice.get(0).conditionName);
			return;
		}

		if (price == null || sVolume.length() <= 0 || sCount.length() <= 0 || selectedDate.length() <= 0) {
			ToastMgr.show(R.string.find_err1);
			return;
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date1 = null;
		Date date2 = new Date(System.currentTimeMillis());
		try {
			date1 = format.parse(selectedDate + ":00");
		} catch (ParseException e) {
			e.printStackTrace();
		}

		if (date1.getTime() - date2.getTime() <= 0) {
			ToastMgr.show("用车时间不能小于当前时间");
			return;
		}

		if (current == 0) {
			if (volume / count < 40) {
				if (volume / count < 20) {
					ToastMgr.show("请至少为每台车分配20方量");
					return;
				}
				final CustomDialog tmpDialog = new CustomDialog(mActivity);
				tmpDialog.show();
				tmpDialog.justShowMsg("建议最少为每台车分配40方量, 是否继续?", new OnClickListener() {
					@Override
					public void onClick(View v) {
						tmpDialog.dismiss();
						dialog.show();
						dialog.justShowMsg("该订单将从账户中冻结¥" + new java.text.DecimalFormat("0.00").format(sumPrice) + "元", new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
								if (!LoginManager.getInstance(mActivity).isLogin()) {
									ToastMgr.show("您还未登录, 请先登录");
									Intent intent = new Intent(mActivity, LoginActivity.class);
									intent.putExtra("fromCreateOrder", true);
									startActivityForResult(intent, 1);
									return;
								}
								manager.submit(LoginManager.getInstance(mActivity).getId(), styles.get(current).styleName, price.condition, price.conditionName == null ? "" : price.conditionName, price.id, volume, price.price, count, selectedDate, sc_addprice.getCount(), remarks, sumPrice, getSubmitListener());
								loadingDialog.show();
							}
						});
					}
				});
				return;
			}
		} else {
			if (volume / count < 50) {
				ToastMgr.show("请至少为每台车分配50方量");
				return;
			}

			if (count > 2) {
				ToastMgr.show("单次下单数量不能超过2台车");
				return;
			}
		}

		dialog.show();
		dialog.justShowMsg("该订单将从账户中冻结¥" + new java.text.DecimalFormat("0.00").format(sumPrice) + "元", new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				if (!LoginManager.getInstance(mActivity).isLogin()) {
					ToastMgr.show("您还未登录, 请先登录");
					Intent intent = new Intent(mActivity, LoginActivity.class);
					intent.putExtra("fromCreateOrder", true);
					startActivityForResult(intent, 1);
					return;
				}
				manager.submit(LoginManager.getInstance(mActivity).getId(), styles.get(current).styleName, price.condition, price.conditionName == null ? "" : price.conditionName, price.id, volume, price.price, count, selectedDate, sc_addprice.getCount(), remarks, sumPrice, getSubmitListener());
				loadingDialog.show();
			}
		});
	}

	private NListener<BaseData> getSubmitListener() {
		return new NListener<BaseData>() {
			@Override
			public void onResponse(BaseData data) {
				loadingDialog.dismiss();
				if (data.status == Constant.STATUS_OK) {
					ToastMgr.show(R.string.find_msg1);
					Intent intent = new Intent(FindTrucksActivity.this, OrderDetailActivity.class);
					intent.putExtra(OrderDetailActivity.ORDER_ID, data.data.orderId);
					startActivity(intent);
					finish();
				} else if (data.status == 8) {
					ToastMgr.show(data.msg);
					startActivity(new Intent(mActivity, RechargeMoneyActivity.class));
				} else if (data.status == 9) {
					ToastMgr.show(data.msg);
					startActivity(new Intent(mActivity, MySitesActivity.class));
				} else {
					ToastMgr.show(data.msg);
				}
			}

			@Override
			public void onErrResponse(VolleyError error) {
				loadingDialog.dismiss();
			}

			@Override
			public void onAllPageLoaded(int nowPage, int totalPage) {
			}
		};
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		System.out.println(requestCode + "---+" + resultCode);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 1:
				loadingDialog.show();
				manager.submit(LoginManager.getInstance(mActivity).getId(), styles.get(current).styleName, price.condition, price.conditionName == null ? "" : price.conditionName, price.id, volume, price.price, count, selectedDate, sc_addprice.getCount(), remarks, sumPrice, getSubmitListener());
				break;
			}
		}
	}

}
